<?php
namespace Admin\Controller;
use Mcit\Page;
//地区运营商管理
class OperationController extends BaseController {

    //首页
    public function index(){
        if(!empty($_GET['oper_login_name'])){
            $map['oper_login_name'] = array('like','%'.I('oper_login_name').'%');
        }
        //分页
        $count = M("operation")->where($map)->order("id")->count();
        vendor('Mcit.Sys.Page');
        $Page = new Page($count, 20);
        $pageView = $Page->show();
        $this->assign('pageView', $pageView); //发送分页
        $nowPage = isset($_GET['page']) ? $_GET['page'] : 1;
        $oper = M("operation")->where($map)->page($nowPage . ',' . $Page->listRows)->order("id")->select();
        foreach($oper as $k=>$v){
            //将数字的地址转换成文字
            $region = strsToArray($v['location']);
            $regionOne = D("Region")->where("code='".$region[1]."'")->field("fullname")->find();
            $oper[$k]['location'] = $regionOne['fullname'];
        
        
            //@lintao 修改：
            //area字段格式:区号1，区号2，...区号n
            //判断area 是否为JSON，否则为老数据:单个区号
            //echo $v['area'];
            $map['area']=array('IN',$v['area']);
            $areas = M("area_code")->where($map)->select();
          
            $map=array();
            if (!empty($v['areas'])){
            	$map['id']=array('IN',$v['areas']);
            	$areas = M("area_code")->where($map)->select();
            }else{
            	if (!empty($v['area'])){
            		$map['area']=array('IN',$v['area']);
            		$areas = M("area_code")->where($map)->select();
            	}
            }
            
            
            
            
            $oper[$k]['areas']=$areas;
        
        
            
            
            
            
            
        }
        //分页结束
        $this->oper = $oper;
        $this->display();
    }
    //运营商详情页
    public function detail(){
        if(IS_GET){
            $oper = M("operation")->where("id='".I('id')."'")->find();
            //将数字的地址转换成文字
            $region = strsToArray($oper['location']);
            $regionOne = D("Region")->where("code='".$region[1]."'")->field("fullname")->find();
            $oper['location'] = $regionOne['fullname'];
            //$this->oper = $oper;
            
            //@lintao 修改：
            //area字段格式:区号1，区号2，...区号n
            //判断area，否则为老数据:单个区号

          
            if (!empty($oper['areas'])){
            	$map['id']=array('IN',$oper['areas']);
            	$areas = M("area_code")->where($map)->select();  
            }else{
            	if (!empty($oper['area'])){
              		$map['area']=array('IN',$oper['area']);
            		$areas = M("area_code")->where($map)->select();     
            	}
            }

            	
            	//echo M()->getLastSql();
     	            
            
            $oper['areas']=$areas;
            $this->oper = $oper;
        }
        $this->display();
    }
    //新增地区运营账户
    public  function addOper(){

        if (IS_GET){
            //@lintao 修改：
            //areas字段格式:地区ID1，地区ID2，...IDn
            //
            //echo $v['area'];

            
         
            $out_areas=M("area_code")->where('')->select();
            

            $oper['outareas']=$out_areas; //不在这些地区里面
            
            $this->oper = $oper;
            
            
            $this->china = D("Region")->getChinaArea();
            
        }
        
        if(IS_POST){

            $time                  = date("Y-m-d H:i:s",time());
            $map['oper_login_name'] = I("oper_login_name");
            if(M('operation')->where($map)->find()){
                $return['state'] = 200;
                $return['msg']   = "此账号已经使用";
                echo json_encode($return);
                exit;
            }

            //上传
            $config = array(
                'maxSize'       =>  3145728, //上传的文件大小限制 (0-不做限制)
                'exts'          =>  array('jpg', 'gif', 'png', 'jpeg'), //允许上传的文件后缀
                'autoSub'       =>  true, //自动子目录保存文件
                'subName'       =>  array('date', 'Ymd'), //子目录创建方式，[0]-函数名，[1]-参数，多个参数使用数组
                'rootPath'      =>     './Public/', //保存根路径
                'savePath'      =>  './data/upload/faces/', //保存路径
                'saveName'      =>  array('uniqid', ''), //上传文件命名规则，[0]-函数名，[1]-参数，多个参数使用数组
            );
            $upload = new \Think\Upload($config); // 实例化上传类
            $info = $upload->uploadOne($_FILES['logo']);
            if (!$info) { // 上传错误提示错误信息
//                $this->error($upload->getError());
            } else { // 上传成功 获取上传文件信息
                $logo     = $info['savepath'].$info['savename'];
            }
            $configs = array(
                'maxSize'       =>  3145728, //上传的文件大小限制 (0-不做限制)
                'exts'          =>  array('jpg', 'gif', 'png', 'jpeg'), //允许上传的文件后缀
                'autoSub'       =>  true, //自动子目录保存文件
                'subName'       =>  array('date', 'YmdHis'), //子目录创建方式，[0]-函数名，[1]-参数，多个参数使用数组
                'rootPath'      =>     './Public/', //保存根路径
                'savePath'      =>  './data/upload/faces/', //保存路径
                'saveName'      =>  array('uniqid', ''), //上传文件命名规则，[0]-函数名，[1]-参数，多个参数使用数组
            );
            $uploads = new \Think\Upload($configs); // 实例化上传类
            $infos = $uploads->uploadOne($_FILES['portrait']);
            if (!$infos) { // 上传错误提示错误信息
//                $this->error($uploads->getError());
            } else { // 上传成功 获取上传文件信息
                $portrait = $infos['savepath'].$infos['savename'];
            }

            $data = $_POST;
            $data['logo']          = $logo;
            $data['portrait']      = $portrait;
            //$data['location']      = I("location_f_1").",".I("location_s_1");
            $data['oper_password'] = sha1("dz123456");
            $data['create_time']   = $time;


            if(I('location_s_1') == 110100 || I('location_s_1') == 120100 || I('location_s_1') == 310100 || I('location_s_1') == 500100){
                $con['code']  = I("location_f_1");
            }else{
                $con['code']  = I("location_s_1");
            }
            $name         = M("region")->where($con)->find();
            $name_text    = mb_substr($name['name'],0,2,"utf8");
            $area         = M("area_code")->where("city like '%".$name_text."%'")->find();
            //$data['area'] = $area['area'];
            
            $data['areas']   =I('inareas');
            
            /* $sql    = "insert into ev_operation(oper_login_name,oper_name,address,location,oper_password,create_time,area,logo,portrait,background,color,areas)
             values('".$data['oper_login_name']."','".$data['oper_name']."','".$data['address']."','".$data['location']."','".$data['oper_password']."','".$data['create_time']."','".$data['area']."','".$data['logo']."','".$data['portrait']."','".$data['background']."','".$data['color']."'" . $areas . "')";
             */
            
            
            if (!empty($data['areas'])){
                $regions=M()->query("select * from ev_region r join ev_area_code a on left(a.city,2)=left(r.name,2) or left(a.city,2)=left(r.fullname,2) where a.id in ({$data['areas']})");
            
                foreach ($regions as $k=>$v ){
                    if ($v['level']==2){
                        $locations[]=array($v['ppcode'],$v['code']);
                    }
                }
   
            }
            
            if (!empty($locations)){
                $loactions_str=json_encode($locations);
                $data['locations']=$loactions_str;

            }
            
  /*                 echo $loactions_str ;
                exit; */          
            
            
            $result = M('operation')->add($data);
            
            $ee= M()->getLastSql();
            
            //$result = M()->query($sql);
            if($result > 0){
                $return['state'] = 100;
                $return['msg']   = '添加成功';
                $return['url']   = U('Operation/index');
            }else{
                $return['state'] = 200;
                $return['msg']   = '添加失败';
            }
            echo json_encode($return);
            exit;
        }
        $this->china = D("Region")->getChinaArea();
        $this->display();
    }
    //修改运营商信息
    public function editOper(){
        if(IS_GET){
            $oper = M("operation")->where("id='".I('id')."'")->find();
            //将数字的地址转换成文字
            $region = strsToArray($oper['location']);
            $regionOne = D("Region")->where("code='".$region[1]."'")->field("fullname")->find();
            $oper['location_text'] = $regionOne['fullname'];
            
            
            //@lintao 修改：
            //areas字段格式:地区ID1，地区ID2，...IDn
            //
            //echo $v['area'];
            $areas_str=$oper['areas'];
            if ($areas_str!=''){
                $map1['id']=array('IN',$areas_str);
                $map2['id']=array('NOT IN',$areas_str);
                
	            $in_areas = M("area_code")->where($map1)->select();
	            $out_areas=M("area_code")->where($map2)->select();                
            }else{
                $map1='';
                $map2='';
                $out_areas = M("area_code")->where($map1)->select();
                
            }
            

  
            $oper['inareas']=$in_areas; //在这些地区里面
               
            $oper['outareas']=$out_areas; //不在这些地区里面
            
            $this->oper = $oper;
            

            $this->china = D("Region")->getChinaArea();
            
            
            //var_dump($in_areas);
            
            
            
            
        }
        if(IS_POST){
            $map['id'] = I("id");
            $data['oper_name'] = I("oper_name");
            $data['address']   = I("address");
            
            $data['areas']=I('inareas');
            //echo $data['areas'];
            
            if(I("location_s") != ''){
                $data['location'] = I("location_f").",".I("location_s");
                $re = M("region")->where("code='".I("location_s")."'")->getField("name");
                if(mb_strlen($re,"utf-8") == 3){
                    $re   = mb_substr($re,0,2,"UTF-8");
                }else if(mb_strlen($re,"utf-8") == 4){
                    $re   = mb_substr($re,0,3,"UTF-8");
                }else if(mb_strlen($re,"utf-8") == 5){
                    $re   = mb_substr($re,0,4,"UTF-8");
                }
                $con['city'] = array("like",$re."%");
                //$data['area'] = M("area_code")->where($con)->getField("area");
            }else{
                //$data['location'] = I("location");
            }
            
            
            
            if (!empty($data['areas'])){
                $regions=M()->query("select * from ev_region r join ev_area_code a on left(a.city,2)=left(r.name,2) or left(a.city,2)=left(r.fullname,2) where a.id in ({$data['areas']})");
            
                foreach ($regions as $k=>$v ){
                    if ($v['level']==2){
                        $locations[]=array($v['ppcode'],$v['code']);
                    }
                }
                 
            }
            
            if (!empty($locations)){
                $loactions_str=json_encode($locations);
                $data['locations']=$loactions_str;
            
            }
            
            
            
            
            
            $result = M('operation')->where($map)->save($data);
            if($result){
                $return['state'] = 100;
                $return['msg']   = '保存成功';
                $return['url']   = U('Operation/index');
            }else{
                $return['state'] = 200;
                $return['msg']   = '保存失败' . M()->getLastSql();
                
            }
            echo json_encode($return);
            exit;
        }
        $this->display();
    }
    
    
    
    
    
    
    
    //密码修改
    public function editOperPwd(){
        if(IS_POST){
            $map['id'] = I("id");
            $map['oper_login_name']  = I("oper_login_name");//账号
            $pwd1  = I("pwd1");//新密码
            $pwd2  = I("pwd2");//重复密码
            if($pwd1 == $pwd2){
                $data['oper_password'] = sha1($pwd2);
                $result = M('operation')->where($map)->save($data);
                if($result){
                    $return['state'] = 100;
                    $return['msg']   = '修改成功';
                    $return['url']   = U('Operation/index');
                }else{
                    $return['state'] = 200;
                    $return['msg']   = '修改失败';
                }
            }else{
                $return['state'] = 200;
                $return['msg']   = '两次密码输入不一致，请重新输入！';
            }
            echo json_encode($return);
            exit;
        }
    }
    //删除运营商账号
    public function delOper(){
        if(IS_AJAX){
            $id = I("id");
            $user          = M("operation")->where("id='".$id."'")->find();
            $logodirs      = strsToArrays($user['logo']);
            $logodir       = APP_ROOT_PATH."./Public/".$logodirs[1]."/".$logodirs[2]."/".$logodirs[3]."/".$logodirs[4];
            if(file_exists(APP_ROOT_PATH."./Public/".$user['logo'])){
                unlink(APP_ROOT_PATH."./Public/".$user['logo']);
            }
            rmdir($logodir);
            $portraitsdirs = strsToArrays($user['portrait']);
            $portraitdir   = APP_ROOT_PATH."./Public/".$portraitsdirs[1]."/".$portraitsdirs[2]."/".$portraitsdirs[3]."/".$portraitsdirs[4];
            if(file_exists(APP_ROOT_PATH."./Public/".$user['portrait'])){
                unlink(APP_ROOT_PATH."./Public/".$user['portrait']);
            }
            rmdir($portraitdir);
            $result = M("operation")->where("id='".$id."'")->delete();
            if($result){
                $return['state'] = 100;
                $return['msg']   = '删除成功';
                $return['url']   = U('Operation/index');
            }else{
                $return['state'] = 200;
                $return['msg']   = '删除失败';
            }
            echo json_encode($return);
            exit;
        }
    }
    

}